var NavBar = require("./navbar/navbar.js");
var Login = require("./login/login.js");
var Arcticle = require("./article/article.js");
var Place = require("./place/place.js");
var Tool = require("./common/tool.js");
var Address = require("./address/address.js");
var EidtPlace = require("./edit-place/editPlace.js");
var NewPlace = require("./new-place/newPlace.js");


// React路由
var ReactRouter = require('react-router');
var hashHistory = ReactRouter.hashHistory;
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var Link = ReactRouter.Link;
var IndexRoute = ReactRouter.IndexRoute;
var IndexRedirect = ReactRouter.IndexRedirect;
var Redirect = ReactRouter.Redirect;
var itemArray = [
    {navTitle:"地点", url:"/place", component:Place},
    {navTitle:"文章", url:"/article", component:Arcticle},
    {navTitle:"精选地点", url:"/address"},
    {navTitle:"添加地点", url:"/place/new"},
    // {navTitle:"添加地点", url:"/place/new"},
    {navTitle:"登出", url:"/loyout"},
    
    
];

// 注意这里的顺序需要和itemArray的一致，在navBar的select active时有影响。
var routeMap = {
    "/login": Login,
    "/place": Place, // 地点
    "/article": Arcticle, // 文章
    "/address":Address, // 精选地点
    "/place/new":NewPlace, // 添加地点
    "/loyout":Login, // 登出
    "/place/:id/edit":EidtPlace, // 编辑地点
   
};

function initComponet(url){
    initBar(url);
    initRouter(url);
}
function initBar(url, index){
    if(document.getElementById('bar')){
        ReactDOM.unmountComponentAtNode(document.getElementById('bar'));
    }
    var Bar;
    if(url=="/login" || url=="/loyout"){
        if(url == "/loyout"){
            // 一、token方式：清掉token
            Tool.clearToken();

            // 二、cookie方式：清掉cookie
            Tool.delCookie('jchTest');
        }
        Bar = null;
    }else{
        Bar = <NavBar items={itemArray} index={index}/>;
    }

    if(Bar){
        ReactDOM.render(
            <div>
                {Bar}
            </div>,
            document.getElementById('bar')
        )
    }
}
function initRouter(url){
     ReactDOM.render(
         
        <div id="container">
           <Router path='/' component={routeMap[url]} >
                         
            {
                Object.keys(routeMap).map(function (item, index) {
                    return (
                        <Router path={item} component={routeMap[item]} onEnter={initBar.bind(this, item, index-1)}/>
                    )
                })
            }
        </Router>
        </div>,
        document.getElementById('content')
    );
}

if(!Tool.getToken()){
    initComponet('/login');
    // location.href="#/login";
}else{
    initComponet('/place');
    // location.href="#/place";
}




